﻿// See https://aka.ms/new-console-template for more information
using Microsoft.AspNetCore.SignalR.Client;
using System.Collections;
using System.Threading.Channels;

Console.WriteLine("Hello, World!");
var connection = new HubConnectionBuilder()
               .WithUrl("https://localhost:51541/hubs/streaming")
               .WithAutomaticReconnect()  // 会自动重新连接 默认是连接失败后等待 0 2 10 30 秒后重连
               .Build();

await connection.StartAsync();

var cancellationTokenSource = new CancellationTokenSource();
var stream = connection.StreamAsync<int>("Counter", 10, 500, cancellationTokenSource.Token);
await foreach (var item in stream)
{
    Console.WriteLine($"Received: {item}");
}
Console.WriteLine("Streaming completed");

Console.ReadKey();

var channel = await connection.StreamAsChannelAsync<int>("CounterChannel", 10, 500, cancellationTokenSource.Token);

// 两个循环都可以读取数据
// wait async for data to be available
/*await foreach (var item in channel.ReadAllAsync(cancellationTokenSource.Token))
{
    Console.WriteLine($"Received from channel: {item}");
}*/

while (await channel.WaitToReadAsync(cancellationTokenSource.Token))
{
    while (channel.TryRead(out var item))
    {
        Console.WriteLine($"Received from channel: {item}");
    }
}
Console.WriteLine("Channel reading completed");

Console.ReadKey();

// 发送数据到服务器

async IAsyncEnumerable<string> clientStreamData()
{
    for (int i = 0; i < 10; i++)
    {
        yield return $"IAsyncEnumerable Message {i + 1}";
        await Task.Delay(500); // Simulate some delay
    }
}

await connection.SendAsync("UploadStream2", clientStreamData());
Console.ReadKey();

var channelWriter = Channel.CreateBounded<string>(10);
await connection.SendAsync("UploadStream", channelWriter.Reader);
for (int i = 0; i < 10; i++)
{
    await channelWriter.Writer.WriteAsync($"Channel Message {i + 1}");
    await Task.Delay(500); // Simulate some delay
}
channelWriter.Writer.Complete(); // Mark the writer as complete

